package com.ruoyi.project.wechatprogram.wxuser.controller;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.project.wechatprogram.moneyoperatelog.domain.WxMoneyOperateLog;
import com.ruoyi.project.wechatprogram.moneyoperatelog.service.IWxMoneyOperateLogService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.wechatprogram.wxuser.domain.WxUser;
import com.ruoyi.project.wechatprogram.wxuser.service.IWxUserService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 员工用户Controller
 *
 * @author xinchen
 * @date 2020-04-12
 */
@Controller
@RequestMapping("/wechatprogram/WxUser")
public class WxUserController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(WxUserController.class);

    private static final String prefix = "wechatprogram/WxUser";
    private static final Integer operate_type_plus = 0;
    private static final Integer operate_type_subtract = 1;
    private static final Integer success = 0;


    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private IWxMoneyOperateLogService moneyOperateLogService;


    @RequiresPermissions("wechatprogram:WxUser:view")
    @GetMapping()
    public String WxUser() {
        return prefix + "/WxUser";
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(String phone, String password) {
        // 判空
        if (StrUtil.isEmpty(phone)) {
            return AjaxResult.error("用户名为空！");
        }
        if (StrUtil.isEmpty(phone)) {
            return AjaxResult.error("密码为空！");
        }
        WxUser wxUser = new WxUser();
        wxUser.setIphone(phone);
        WxUser wxUserByUser = wxUserService.selectWxUserByUser(wxUser);
        if (wxUserByUser == null) {
            return AjaxResult.error("用户不存在！");
        } else {
            if (phone.equals(wxUserByUser.getIphone()) && password.equals(wxUserByUser.getPassword())) {
                return AjaxResult.success(wxUserByUser);
            } else {
                return AjaxResult.error("登录失败！");
            }
        }
    }

    /**
     * 查询员工用户列表
     */
    @RequiresPermissions("wechatprogram:WxUser:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxUser wxUser) {
        startPage();
        List<WxUser> list = wxUserService.selectWxUserList(wxUser);
        return getDataTable(list);
    }

    /**
     * 查询员工用户列表
     */
    @PostMapping("/wxlist")
    @ResponseBody
    public AjaxResult wxlist(String phone) {
        WxUser wxUser = new WxUser();
        wxUser.setIphone(phone);
        WxUser wxUserByUser = wxUserService.selectWxUserByUser(wxUser);
        return AjaxResult.success(wxUserByUser);
    }

    /**
     * 导出员工用户列表
     */
    @RequiresPermissions("wechatprogram:WxUser:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WxUser wxUser) {
        List<WxUser> list = wxUserService.selectWxUserList(wxUser);
        ExcelUtil<WxUser> util = new ExcelUtil<WxUser>(WxUser.class);
        return util.exportExcel(list, "WxUser");
    }

    /**
     * 新增员工用户
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存员工用户
     */
    @RequiresPermissions("wechatprogram:WxUser:add")
    @Log(title = "员工用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WxUser wxUser) {
        return toAjax(wxUserService.insertWxUser(wxUser));
    }

    /**
     * 批量新增员工的余额
     */
    @RequiresPermissions("wechatprogram:WxUser:addAllBalance")
    @GetMapping("/addAllBalance")
    public String addAllBalance() {
        return prefix + "/addAllBalance";
    }

    /**
     * 批量保存新增员工的余额
     */
    @RequiresPermissions("wechatprogram:WxUser:addAllBalanceSave")
    @Log(title = "员工用户", businessType = BusinessType.INSERT)
    @PostMapping("/addAllBalanceSave")
    @ResponseBody
    public AjaxResult addAllBalanceSave(Integer number) {
        WxUser wxUser = new WxUser();
        wxUser.setDel(0);
        List<WxUser> userList = wxUserService.selectWxUserList(wxUser);
        if (userList.size() < 0) {
            AjaxResult.success("批量增加员工余额异常！");
        }
        for (WxUser user : userList) {
            Integer balance = user.getBalance();
            user.setBalance(balance + number);
        }
        AjaxResult ajaxResult = wxUserService.updateUserBalanceByAll(userList);
        Integer code= (Integer)ajaxResult.get("code");
        if(code == success){
            //添加金额变动记录
            try {
                List<WxMoneyOperateLog> moneyOperateLogList = new ArrayList<>();
                WxMoneyOperateLog moneyOperateLog = null;
                for (WxUser user : userList) {
                    moneyOperateLog = new WxMoneyOperateLog();
                    moneyOperateLog.setUserId(user.getId());
                    moneyOperateLog.setIphone(user.getIphone());
                    moneyOperateLog.setName(user.getName());
                    moneyOperateLog.setType(operate_type_plus);
                    moneyOperateLog.setBalanceChange(number);
                    moneyOperateLog.setBalance(user.getBalance());
                    moneyOperateLog.setDescription("管理员批量增加员工余额");
                    moneyOperateLog.setCreateTime(DateUtils.getNowDate());
                    moneyOperateLogList.add(moneyOperateLog);
                }
                moneyOperateLogService.insertWxMoneyOperateLogList(moneyOperateLogList);
            }catch (Exception e){
                log.error("批量增加员工余额操作，添加记录异常！",e);
            }
        }
        return ajaxResult;
    }

    /**
     * 修改员工用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        WxUser wxUser = wxUserService.selectWxUserById(id);
        mmap.put("wxUser", wxUser);
        return prefix + "/edit";
    }

    /**
     * 修改保存员工用户
     */
    @RequiresPermissions("wechatprogram:WxUser:edit")
    @Log(title = "员工用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WxUser wxUser) {
        return toAjax(wxUserService.updateWxUser(wxUser));
    }

    /**
     * 微信端修改密码
     */
    @Log(title = "员工用户", businessType = BusinessType.UPDATE)
    @PostMapping("/wxedit")
    @ResponseBody
    public AjaxResult wxEditSave(String phone, String passwordold, String passwordnew) {
        // 判空
        if (StrUtil.isEmpty(phone)) {
            log.debug("用户手机号为空！");
            return AjaxResult.error("手机号不能为空！");
        }
        if (StrUtil.isEmpty(passwordold)) {
            log.debug("用户老密码为空！");
            return AjaxResult.error("老密码不能为空！");
        }
        if (StrUtil.isEmpty(passwordnew)) {
            log.debug("用户新密码为空！");
            return AjaxResult.error("新密码不能为空！");
        }
        WxUser wxUser = new WxUser();
        wxUser.setIphone(phone);
        // 根据用户手机号码查询当前用户
        WxUser wxUserByPhone = wxUserService.selectWxUserByUser(wxUser);
        if (wxUserByPhone == null) {
            return AjaxResult.error("用户不存在！");
        }
        // 判断用户输入的老密码是否一致
        if (!wxUserByPhone.getPassword().equals(passwordold)) {
            log.debug("老密码输入错误！");
            return AjaxResult.error("老密码输入错误！");
        }
        // 修改密码
        wxUser.setPassword(passwordnew);
        Integer successStatus = wxUserService.updateWxUserPasswordByPhone(wxUser);
        if (successStatus <= 0) {
            log.debug("更新密码失败！");
            return AjaxResult.error("更新密码失败！");
        }
        return AjaxResult.success(wxUserService.selectWxUserByUser(wxUser));
    }

    /**
     * 删除员工用户
     */
    @RequiresPermissions("wechatprogram:WxUser:remove")
    @Log(title = "员工用户", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(wxUserService.deleteWxUserByIds(ids));
    }

    @Log(title = "员工管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("wechatprogram:WxUser:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<WxUser> util = new ExcelUtil<WxUser>(WxUser.class);
        List<WxUser> wxUserList = util.importExcel(file.getInputStream());
        String message = wxUserService.importWxUser(wxUserList, updateSupport);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("wechatprogram:WxUser:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<WxUser> util = new ExcelUtil<WxUser>(WxUser.class);
        return util.importTemplateExcel("员工数据");
    }

    /**
     * 重置密码（xc）
     */
    @RequiresPermissions("wechatprogram:WxUser:resetPassword")
    @Log(title = "员工用户", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPassword/{id}")
    @ResponseBody
    public AjaxResult resetPassword(@PathVariable("id") Integer id) {
        if (StrUtil.isBlankIfStr(id)) {
            log.debug("重置密码失败！！！获取的id为：" + id);
            return AjaxResult.error("重置密码失败！");
        }
        boolean isSuccess = false;
        isSuccess = wxUserService.resetPassword(id) > 0;
        if (isSuccess) {
            return AjaxResult.success("重置密码成功");
        }
        return AjaxResult.error("重置密码异常！");
    }

    /**
     * 修改员工余额
     */
    @GetMapping("/editBalance/{id}")
    public String editBalance(@PathVariable("id") Integer id, ModelMap mmap) {
        WxUser wxUser = wxUserService.selectWxUserById(id);
        mmap.put("wxUser", wxUser);
        return prefix + "/editBalance";
    }

    /**
     * 修改保存员工余额
     */
    @RequiresPermissions("wechatprogram:WxUser:editBalanceSave")
    @Log(title = "员工用户", businessType = BusinessType.UPDATE)
    @PostMapping("/editBalanceSave")
    @ResponseBody
    public AjaxResult editBalanceSave(Integer id, Integer balance) {
        if (StrUtil.isBlankIfStr(id)) {
            AjaxResult.error("修改金额失败");
        }
        if (StrUtil.isBlankIfStr(balance)) {
            AjaxResult.error("修改金额失败，变更的金额不能为空");
        }
        //查询员工
        WxUser user = new WxUser();
        user = wxUserService.selectWxUserById(id);
        boolean isSuccess = false;
        WxUser wxUser = new WxUser();
        wxUser.setId(id);
        wxUser.setBalance(balance);
        isSuccess = wxUserService.updateWxUser(wxUser) > 0;
        if (isSuccess) {
            //添加员工金额变动记录
            WxMoneyOperateLog moneyOperateLog = new WxMoneyOperateLog();
            moneyOperateLog.setUserId(user.getId());
            moneyOperateLog.setIphone(user.getIphone());
            moneyOperateLog.setName(user.getName());
            if (balance >= user.getBalance()) {
                moneyOperateLog.setType(operate_type_plus);
            } else {
                moneyOperateLog.setType(operate_type_subtract);
            }
            if (balance >= user.getBalance()) {
                moneyOperateLog.setBalanceChange(balance - user.getBalance());
            } else {
                moneyOperateLog.setBalanceChange(user.getBalance() - balance);
            }
            moneyOperateLog.setBalance(balance);
            moneyOperateLog.setDescription("管理员修改员工余额");
            moneyOperateLogService.insertWxMoneyOperateLog(moneyOperateLog);
            return AjaxResult.success("修改金额成功");
        }
        return AjaxResult.error("修改金额异常");
    }

}
